<?php

class Admin_Table_Accounts extends Apk_Db_Table
{
    protected $_name      = 'accounts';
    protected $_primary   = 'id';

    protected $_referenceMap    = array(
                                        'Role' => array(
                                            'columns'           => 'role_id',
                                            'refTableClass'     => 'Admin_Table_Role',
                                            'refColumns'        => 'id'
                                        )
                                    );

    public $_ERROR = '';
    public $_lang = 'ru';

    public function GetError()
    {
    	return $this->_ERROR;
    }


    public function GetDataRow($id)
    {
    	$sel = $this->getAdapter()->select()
    				->from($this->_name)
    				->where('id = ?', $id);

    	return $this->setDecorator('simpleDecorator')->getList($sel)->getRow(0)->toArray();

    }


    public function GetDataList($page = 1, $sort=null, $page_count=null, $search = array())
    {
		$sel = $this->getAdapter()->select()
			->from($this->_name, array('id', 'path', 'username', 'last_name', 'first_name', 'add_date', 'is_active', 'file_name'))
			->join('accounts_roles', 'accounts.role_id = accounts_roles.id', array('role_name' => 'name_full'))
			->where('accounts.is_ghost = 0')
			->where('accounts.is_removed = 0');

		if(count($search) > 0)
		foreach($search as $k => $v)
		{
			switch ($k)
			{
				case 'search_text':
					if(trim($v) != '')
					$sel->where('accounts.username like \'%'.$v.'%\' or accounts.last_name like \'%'.$v.'%\' or accounts.first_name like \'%'.$v.'%\' ');
					break;
				case 'is_active':
					if(intval($v) >= 0 && trim($v) != '')
					$sel->where('accounts.'.$k.' = ?', intval($v));
					break;
				case 'role':
					if(intval($v) != 1)
						$sel->where('accounts.role_id != 1');
                                        if(intval($v) == 12)
						$sel->where('accounts.role_id = 14 OR accounts.role_id = 15');
                                        
					break;
				default:
					if(intval($v) > 0)
					$sel->where('accounts.'.$k.' = ?', $v);
			}
		}
//echo $sel;die();
		if(strlen($sort) > 0) $sel->order($this->_name.'.'.$sort);

		return  $this->setDecorator('simpleDecorator')->getPager($sel, $page, array('perPage' => $page_count));

    }
					/***/
	public function GetUserCats($id)
    {
		$sel = $this->getAdapter()->select()
			->from('accounts_cats_rel')
			->join('categories', 'categories.id = accounts_cats_rel.id_cat', array('name'=>'menu_name_ru'))
			->where('accounts_cats_rel.id_acc = ?', $id);


		$data =  $this->getList($sel)->toArray();

		$ret = '';

		if(isset($data[0]['name']))
		foreach($data as $k => $v)
		{
			if($k != 0) $ret .= ', ';
			$ret .= $v['name'];
		}

		return $ret;
    }

    public function GetUsers()
    {
		$sel = $this->getAdapter()->select()
			->from($this->_name)
			->where('accounts.is_active')
			->where('accounts.is_ghost = 0')
			->where('accounts.is_removed = 0')
			->order('username');

		return $this->getList($sel)->toArray();
    }


    public function GetPrivilegeList($id_cat)
    {
		$cats[] = 0;
		$cats[] = $id_cat;

        $sel = $this->getAdapter()->select()
			->from('accounts_privileges')
			->where('id_cat in (?)', $cats)
			->order('norder');

		return $this->getList($sel)->toArray();
    }
    
    /**/
	public function GetUserCount($opt = null)
    {
        switch ($opt){
               case 'online':
                   $sel = $this->getAdapter()->select()
								->from('accounts')
					                        ->where(time().' - accounts.online_date < 300')
								->where('accounts.is_ghost = 0')
								->where('accounts.is_removed = 0');
                   break;

               default:
                   $sel = $this->getAdapter()->select()
								->from('accounts')
								->where('accounts.is_ghost = 0')
								->where('accounts.is_removed = 0');
                   break;
        }
        return $this->getList($sel)->count();
    }

    //********************************************
    // Update information
    //********************************************

	public function insert(array $data, $user_id)
    {
        $data['add_date'] = time();
        $data['modify_date'] = time();
        $data['birth_date'] = time();

        $data['add_user_id'] = $user_id;
        $data['modify_user_id'] = $user_id;

    	return parent::insert($data);
    }

    public function update($data, $id, $user_id)
    {
        if($data['koatuu'] == ''){
            $this->_ERROR = 'Недопустимий КОАТУУ';
            return false;
        }
    	if($data['pass1'] != '')
			if(!($data['password']  = $this->check_password($data['pass1'], $data['pass2']))) return false;


    	$data['modify_user_id'] = $user_id;
    	$data['modify_date'] = time();
    	$data['is_ghost'] = 0;
        $data['koatuu'] = str_pad($data['koatuu'], 10, "0", STR_PAD_LEFT);

		unset($data['pass1']);
		unset($data['pass2']);

		//print_r($data); die();

		return parent::update($data, 'id = '.$id);
    }

    public function change_role($role_id, $id, $user_id)
    {
    	$data['modify_user_id'] = $user_id;
    	$data['modify_date'] = time();
    	$data['role_id'] = $role_id;

    	return parent::update($data, 'id = '.$id);
    }

    public function remove($items, $user_id)
    {
    	foreach($items as $k => $id)
    	{
	    	$data['modify_user_id'] = $user_id;
	    	$data['modify_date'] = time();
	    	$data['is_removed'] = 1;

	    	parent::update($data, 'id = '.$id);
    	}

    	return true;
	}

	//************************************************/
	// Getting data for listing
	//************************************************/

	public function GetRolesList($a = null, $role = 1)
    {
    	$ret = array();

		$sel = $this->getAdapter()->select()
						->from('accounts_roles', array('id', 'name', 'name_full'))
						->where('is_ghost = 0')
						->where('is_removed = 0')
						->where('is_active')
						->order('norder');

		if($role != 1) $sel->where('id != 1');

		$data = $this->getList($sel)->toArray();

    	if(count($data) > 0 && !is_null($a))
    	foreach($data as $k => $v)
    	  	if($v['id'] == $a) $data[$k]['__attributes']['active'] = 1;

    	return $data;
    }
    
	public function GetActiveList($a)
    {
            $data = array(
                    array('id' => 1, 'name' => 'активный'),
                    array('id' => 0, 'name' => 'не активный')
            );

        foreach($data as $k => $v)
            if($v['id'] == $a && !is_null($a)) $data[$k]['__attributes']['active'] = 1;

        return $data;
    }

    //************************************************/
    // Checking data functions
	//************************************************/

    public function check_login($val)
    {
		$val = strtolower(trim($val));

        if($val == ''){
        	$this->_ERROR = 'Необходимо ввести Логин';
        	return false;
        }

		$sel = $this->select()->from($this->_name)
				->where('username = ?', $val);
		$data = $this->getAdapter()->fetchAll($sel);
		if(count($data) > 0)
		{
			$this->_ERROR = 'Такой Логин уже существует.';
			return false;
		}
		return $val;
    }

    public function check_email($val)
    {
		$val = trim($val);
        if($val == ''){
        	$this->_ERROR = 'Необходимо ввести E-mail';
        	return false;
        }

    	$vald_email = new Zend_Validate_EmailAddress();
        if(!$vald_email->isValid($val))
        {
           $this->_ERROR = implode(',', $vald_email->getMessages());
           return false;
        }
		$sel = $this->getAdapter()->select()->from($this->_name)->where('email = ?', $val);
		$data = $this->getAdapter()->fetchAll($sel);
		if(count($data) > 0)
		{
			$this->_ERROR = 'Пользователь с таким E-mail уже существует.';
			return false;
		}

		return $val;
    }

    public function check_password($pass1, $pass2)
    {
        if($pass1 == ''){
        	$this->_ERROR = 'Необходимо ввести пароль';
        	return false;
        }

        if($pass2 == ''){
        	$this->_ERROR = 'Необходимо подтвердить пароль';
        	return false;
        }

        if($pass1 != $pass2){
        	$this->_ERROR = 'Неверное подтверждение пароля';
        	return false;
        }

        return md5($pass1);
    }


    //************************************************/
    //  Decorators
    //************************************************/

    public function simpleDecorator($key, $value)
    {
        switch ($key) {
            case 'add_date':
            case 'modify_date':
            case 'birth_date':
            	$result[$key]['__attributes'] = $this->timestampToArray($value);
            	break;
            case 'koatuu':
                $result[$key] = str_pad($value, 10, "0", STR_PAD_LEFT);
                break;
            default:
                $result[$key] = trim(stripslashes($value));
                break;
        }
        return $result;
    }

}
?>
